package com.fourthGroup.service.impl;

import com.fourthGroup.model.Activity;
import com.fourthGroup.service.ActivityService;
import com.fourthGroup.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ActivityServiceImpl implements ActivityService {

    // 使用内存存储活动信息（实际项目中应使用数据库）
    private final Map<Long, Activity> activityMap = new ConcurrentHashMap<>();
    private Long activityIdGenerator = 1L;

    @Override
    public Result<Activity> createActivity(Activity activity) {
        // 设置ID和创建时间
        activity.setId(activityIdGenerator++);
        activity.setCreateTime(new Date());
        
        // 根据开始和结束时间设置状态
        Date now = new Date();
        if (now.before(activity.getStartTime())) {
            activity.setStatus(0); // 未开始
        } else if (now.after(activity.getEndTime())) {
            activity.setStatus(2); // 已结束
        } else {
            activity.setStatus(1); // 进行中
        }
        
        activityMap.put(activity.getId(), activity);
        log.info("创建活动成功: {}", activity);
        return Result.success(activity);
    }

    @Override
    public Result<List<Activity>> listActivities() {
        List<Activity> activities = new ArrayList<>(activityMap.values());
        return Result.success(activities);
    }

    @Override
    public Result<Activity> getActivity(Long id) {
        Activity activity = activityMap.get(id);
        if (activity == null) {
            return Result.error("活动不存在");
        }
        return Result.success(activity);
    }

    @Override
    public Result<Activity> updateActivity(Activity activity) {
        if (!activityMap.containsKey(activity.getId())) {
            return Result.error("活动不存在");
        }
        
        // 更新活动
        Activity existingActivity = activityMap.get(activity.getId());
        activity.setCreateTime(existingActivity.getCreateTime());
        
        // 更新状态
        Date now = new Date();
        if (now.before(activity.getStartTime())) {
            activity.setStatus(0); // 未开始
        } else if (now.after(activity.getEndTime())) {
            activity.setStatus(2); // 已结束
        } else {
            activity.setStatus(1); // 进行中
        }
        
        activityMap.put(activity.getId(), activity);
        log.info("更新活动成功: {}", activity);
        return Result.success(activity);
    }
} 